import org.deltaset.support.gen.AbstractGenWriter;
import org.deltaset.support.meta.MetaModelFactory;

public class PersistenceWriter extends AbstractGenWriter{

    public boolean isSatisfied(){
        return true;
    }
    
    public void write(){
        if(true==getContext().getOverwrite()){
            return;
        }
        def dsonString = getContext().getCommandContext();
        def model = MetaModelFactory.fromDsonString(dsonString, getContext().getPackageName());
        def baseDir = getContext().getBaseDir();
        PersistenceWriter.write(baseDir,model);
        model.fields.each{f->
            if(!f.fields.isEmpty()){
                PersistenceWriter.write(baseDir,f);
            }
        }
    }
    
    static void write(baseDir,model){  
        def fileName = "/src/main/resources/META-INF/persistence.xml"    
        File menuFile=new File(baseDir,fileName)
        def allLines = menuFile.readLines()
        def changedLines=[]
                
        
        allLines.each{line ->
            if(line.contains("<properties>")){
                changedLines.add("    <class>${model.packageName}.domain.${model.typeClassLike}</class>")
            }
            changedLines.add(line)
        }
        menuFile.withWriter{file ->
            changedLines.each{line ->
                file.writeLine(line)
            }
        }
    }
}